package com.cqz.action;

import com.cqz.dao.UserInfo;
import com.cqz.services.UserService;
import com.cqz.tools.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
public class LoginAction {

    @Autowired
    private UserService userService;

    /**
     * 登录
     * @param httpSession
     * @param user_name
     * @param user_password
     * @return
     */
    @RequestMapping("loginAction")
    public String login(HttpSession httpSession,String user_name,String user_password){
        httpSession.removeAttribute("userNameOrPassword");
        UserInfo userInfo=null;
        if(Tools.isNull(user_name)){
            return "login";
        }else if(Tools.isNull(user_password)){
            return "login";
        }else {
            userInfo=userService.checkUser(user_name,user_password);

            if(userInfo==null||userInfo.getUstate().equals("0")){
                httpSession.setAttribute("userNameOrPassword","用户名或密码错误");
                return "login";
            }else if(userInfo.getUstate().equals("x")){
                httpSession.setAttribute("userNameOrPassword","用户已注销");
                return "login";
            }else {
                httpSession.setAttribute("user_name", user_name);
                httpSession.setAttribute("isLogin",true);
                httpSession.setAttribute("sessionid",httpSession.getId());
                httpSession.setAttribute("state",userInfo.getUstate());
                httpSession.setAttribute("uid",userInfo.getUid());
                httpSession.setAttribute("money",userInfo.getUamount());
                httpSession.setAttribute("address",userInfo.getUaddress());
                return "redirect:homeAction";
            }
        }
    }

    /**
     * 退出登录
     * @param httpSession
     * @return
     */
    @RequestMapping("logoutAction")
    public String logout(HttpSession httpSession){
        httpSession.removeAttribute("user_name");
        httpSession.removeAttribute("sessionid");
        boolean isLogin = false;
        httpSession.setAttribute("isLogin",isLogin);
        return "redirect:loginAction";
    }
}
